package command;

import java.util.Iterator;
import java.util.List;

import elements.Robot;
import exceptions.IllegalCommandException;
/**
 * A class of composed command representing the sequence command.
 * 
 * @version	3.0
 * @author 	Lies Tambeur 	r0264469	2Bcwsbbh
 * @author	Eline Vanrykel	r0264543	2Bcwselt
 */
public class Sequence extends ComposedCommand {
	/**
	 * Initialize the new Sequence with the given list of commands.
	 * @param 	commands
	 * 			The list of commands for the new Sequence.
	 * @post	The given list of commands will be the same as the commands from the new Sequence.
	 */
	public Sequence(List<Command> commands){
		Iterator<Command> it = commands.iterator();
		while(it.hasNext()){
			if(!canHaveAsCommand(it.next())){
				throw new IllegalCommandException();
			}
		}
		this.commands = commands;
	}

	/**
	 * The list of commands from the sequence.
	 */
	private List<Command> commands;
	/**
	 * Returns commands
	 * @return	the commands from the sequence.
	 */
	private List<Command> getCommands(){
		return this.commands;
	}
	/**
	 * Executes every command from commands.
	 */
	@Override
	public void execute(Robot robot) {
		Iterator<Command> it = this.getCommands().iterator();
		while(it.hasNext()){
			it.next().execute(robot);
		}
	}
	
	@Override
	public String toString(){
		String result = "(seq ";
		Iterator<Command> commands = this.getCommands().iterator();
		while(commands.hasNext()){
			result = result + commands.next().toString();
		}
		return result+" )";
	}
	
	@Override
	public boolean equals(Object object){
		if(object == null || this==null){
			return false;
		}
		return this.toString().equals(object.toString());
	}
	
	@Override
	public void setAlreadyExecuted(boolean alreadyExecuted){
		this.alreadyExecuted = alreadyExecuted;
		Iterator<Command> it = this.getCommands().iterator();
		while(it.hasNext()){
			it.next().setAlreadyExecuted(alreadyExecuted);
		}
	}

	@Override
	public boolean executeSingleStep(Robot robot) {
		if(!this.isAlreadyExecuted()){
			Iterator<Command> it = this.getCommands().iterator();
			while(it.hasNext()){
				if(it.next().executeSingleStep(robot)){
					if(!it.hasNext()){
						this.setAlreadyExecuted(true);
					}
					return true;
				}
			}
		}
		return false;
	}
}
